var setter ;
layui.use(['setter'], function() {
    setter = layui.setter;
});

layui.define([], function(exports){
    var $ = layui.$,
    form = layui.form,
    table = layui.table,
    totalFilter = layui.totalFilter,
    colorpicker = layui.colorpicker,
    element = layui.element,
    layer = layui.layer,
    slider = layui.slider,
    formName = '.form-props-info-scroll',
    temPropOpt = 'temPropOpt',
    temProps = 'temProps',
    propSlideOnly = '.propSlideOnly',
    selectStamp = '.selectStamp',
    optName = 'optName',
    defPropName = 'defPropName',
    colorInit = function(name,_color,callback){
        colorpicker.render({
            elem:name.find('.temColorVal'),
            color: _color,
            done: function(color){
                name.find('.temColorInput').val(color);
                typeof callback == "function" ? callback(color) : null;
            }
        });
    },
    propsHandle = function(obj){
        form.render();
        element.init();
        var formData = {},
        tag = $(selectStamp +' ');
        if(obj){
            formData = obj;
        }

        // 滑动条集合---------------------------
        var sliderObj = $('.'+temProps+' '+propSlideOnly);
        if(sliderObj.length > 0){
            var textDisplay = 'textDisplay',
                textDisplayName = $('[lay-filter='+textDisplay+']').attr('name'),
                textTitleSite = 'textTitleSite',
                textTitleSiteName = $('[lay-filter='+textTitleSite+']').attr('name'),
                sliderObjLabel = tag.find('.'+sliderObj.attr('optLeft')),
                sliderObjInput= tag.find('.'+sliderObj.attr('optRight')),
                isType = (sliderObjLabel.css('float') === 'left'),
                sliderInputW = parseInt(((parseInt(sliderObjInput.css('width'),10) / parseInt(sliderObjInput.parent().css('width'),10))*100),10),
                sliderLabelW = parseInt(((parseInt(sliderObjLabel.css('width'),10) / parseInt(sliderObjLabel.parent().css('width'),10))*100),10);
            
            formData[textTitleSiteName] = sliderObjLabel.css('float');
            formData[textDisplayName] = sliderObjLabel.css('display');
            
                // 滑动
            slider.render({
                elem:propSlideOnly,
                value: isType ? [sliderLabelW,(sliderInputW + sliderLabelW)]: sliderInputW,
                range: isType,
                max : 100,
                min : isType ? 10 : 0,
                change: function(e){
                    timers(function(){
                        if(isType){
                        var labelW = (e[0] >= 99 ? 98 : e[0]),inputW = ((e[1] - e[0]) <= 2 ? 2:(e[1] - e[0]));
                        sliderObjInput.css('width',inputW+'%');
                        sliderObjLabel.css('width',labelW+'%');
                        }else{
                        sliderObjInput.css('width',e+'%');
                        }
                    });
                }
            });


            form.on('radio('+textDisplay+')',function(data){
                var isLabel = $('[name='+textTitleSiteName+']')[0].checked;
                if(isLabel){
                  sliderObjLabel.css('display',data.value);
                }else{
                  sliderObjLabel.css('display','block');
                  sliderObjLabel.css('visibility',data.value === 'none'?'hidden':'inherit');
                }
            });

            form.on('radio('+textTitleSite+')', function(data){
                var isBool =(data.value === 'left'),isLabel = $('[name='+textDisplayName+']')[0].checked;
                sliderObjInput.css('width',isBool ? '90%' : '100%');
                sliderObjLabel.css('width',isBool ? '10%' : '100%').css('float',data.value);
                if(!isLabel){
                  sliderObjLabel.css('display', isBool ? 'block' : 'none');
                  sliderObjLabel.css('visibility',isBool ? 'hidden': 'inherit');
                }
        
                slider.render({
                  elem:propSlideOnly,
                  value: 100,
                  range: isBool,
                  max : 100,
                  min : isBool ? 10 : 0,
                  change: function(e){
                    timers(function(){
                      if(isBool){
                        var labelW = (e[0] >= 99 ? 98 : e[0]),inputW = ((e[1] - e[0]) <= 2 ? 2:(e[1] - e[0]));
                        sliderObjInput.css('width',inputW+'%');
                        sliderObjLabel.css('width',labelW+'%');
                      }else{
                        sliderObjInput.css('width',e+'%');
                      }
                    });
                    
                  }
               });
        
            });

        }


        // ------------------------------------------


        // input value 类型

        $(formName).find('.temInput').each(function(){
            var _name = $(this).attr(optName);
            formData[$(this).attr('name')] = $(selectStamp + (!!_name?' .'+_name:'') ).css($(this).attr(temPropOpt));
            $(this).keydown(function(){
                var _this = $(this),
                _thisName = _this.attr(optName);
                timers(function(){
                    $(selectStamp + (!!_thisName?' .'+_thisName:'') ).css(_this.attr(temPropOpt),_this.val());
                });
            });


        });

        $(formName).find('.temInputAttr').each(function(){
            var _name = $(this).attr(optName);
            formData[$(this).attr('name')] = $(selectStamp + (!!_name?' .'+_name:'') ).attr($(this).attr(temPropOpt));
            $(this).keydown(function(){
                var _this = $(this),
                _thisName = _this.attr(optName);
                timers(function(){
                    $(selectStamp + (!!_thisName?' .'+_thisName:'') ).attr(_this.attr(temPropOpt),_this.val());
                });
            });


        });


        // select 
        $(formName).find('.temSelect').each(function(){
            var _name = $(this).attr(optName);
            formData[$(this).find('select').attr('name')] = $(selectStamp + (!!_name?' .'+_name:'') ).css($(this).attr(temPropOpt));
        });
        form.on('select(temSelect)', function(data){
            var _name = $(this).attr(optName),
            _opt = $(this).parents('.temSelect').attr(temPropOpt);
            $(selectStamp + (!!_name?' .'+_name:'') ).css(_opt,data.value);
        });

        // radio 
        $(formName).find('.temRadio').each(function(){
            var _name = $(this).attr(optName);
            formData[$(this).find('input').attr('name')] = $(selectStamp + (!!_name?' .'+_name:'') ).css($(this).attr(temPropOpt));
        });

        form.on('radio(temRadio)', function(data){
            var _name = $(this).parents('.temRadio').attr(optName),
            _opt = $(this).parents('.temRadio').attr(temPropOpt);
            $(selectStamp + (!!_name?' .'+_name:'') ).css(_opt,data.value);
        });

        $(formName).find('.temRadioAttr').each(function(){
            var _name = $(this).attr(optName);
            formData[$(this).find('input').attr('name')] = $(selectStamp + (!!_name?' .'+_name:'') ).attr($(this).attr(temPropOpt));
        });

        form.on('radio(temRadioAttr)', function(data){
            var _name = $(this).parents('.temRadioAttr').attr(optName),
            _opt = $(this).parents('.temRadioAttr').attr(temPropOpt);
            $(selectStamp + (!!_name?' .'+_name:'') ).attr(_opt,data.value);
        });



        
    
        // text 赋值类型
        $(formName).find('.temText').each(function(){
            var _name = $(this).attr(optName);
            formData[$(this).attr('name')] = $.trim($(selectStamp + (!!_name?' .'+_name:'') ).text());

            $(this).keydown(function(){
                var _this = $(this),
                _thisName = _this.attr(optName);
                timers(function(){
                    $(selectStamp + (!!_thisName?' .'+_thisName:'') ).text(_this.val());
                    form.render();
                });
            });

        });


        // color

        $(formName).find('.temColor').each(function(){
            var _this = $(this),
            _name = $(this).attr(optName),
            _color = $(selectStamp + (!!_name?' .'+_name:'') ).css(_this.attr(temPropOpt)).colorHex(),
            _input = _this.find('.temColorInput');
            _input.val(_color);
            colorInit(_this,_color,function(color){
                $(selectStamp + (!!_name?' .'+_name:'') ).css(_this.attr(temPropOpt),color);
            });
            _input.keydown(function(){
                var that = $(this);
                timers(function(){
                    colorInit(_this,that.val(),function(color){
                        $(selectStamp + (!!_name?' .'+_name:'') ).css(_this.attr(temPropOpt),color);
                    });
                    $(selectStamp + (!!_name?' .'+_name:'') ).css(_this.attr(temPropOpt),that.val());
                });
            });

        });



        form.val(temProps, formData);


        $('.addProperty').click(function(){
            $('.addPropsHandle').append('<div class="form-props-input"><input type="text" autocomplete="off" class="layui-input propKey"><input type="text" autocomplete="off" class="layui-input propVal"><i class="layui-icon layui-icon-delete itemDel"></i></div>');
        });

        $('.addPropsHandle').on('click','.itemDel',function(){
            var _name = $('.addPropsHandle').attr(optName),
            selectObj = $(selectStamp + (!!_name?' .'+_name:'') ),
            key = $(this).parent().find('.propKey').val();
            if(/^[a-z][a-z0-9_-]*$/.test(key)){
                $(selectStamp + (!!_name?' .'+_name:'') ).removeAttr(key);
            }
            $(this).parent().remove();
        });


        var _stampName = $('.addPropsHandle').attr(optName),
        defPropList = !!$('.addPropsHandle').attr(defPropName) ? $('.addPropsHandle').attr(defPropName).split(','):[];
        $('.addPropsHandle').html('');
        $(selectStamp + (!!_stampName?' .'+_stampName:'') ).each(function() {
            $.each(this.attributes, function(i) {
                if(this.specified){
                    var isHide = defPropList.indexOf(this.name) > -1;
                    $('.addPropsHandle').append('<div class="form-props-input"><input type="text" autocomplete="off" '+(isHide?('disabled="disabled"'):'')+' value="'+this.name+'" class="layui-input propKey"><input type="text" '+(isHide?('disabled="disabled"'):'')+' autocomplete="off" value="'+this.value+'" class="layui-input propVal">'+(isHide?'':'<i class="layui-icon layui-icon-delete itemDel"></i>')+'</div>');
                }
            });
        });

        $('.addPropsHandle').on('keydown','.form-props-input input',function(){
            var that = $(this);
            timers(function(){
                var _name = $('.addPropsHandle').attr(optName),
                selectObj = $(selectStamp + (!!_name?' .'+_name:'') ),
                selectAttr = [];
                selectObj.each(function() {
                    $.each(this.attributes, function() {
                        if(this.specified&& defPropList.indexOf(this.name) < 0){
                            selectAttr.push(this.name);
                        }
                    });
                });
                
                selectObj.removeAttr(selectAttr.join(' '));
                
                $('.addPropsHandle .form-props-input').each(function(i,item){
                    var key = $(item).find('.propKey').val();
                    if(!!key){
                        if( /^[a-z][a-z0-9_-]*$/.test(key)){
                            var val = $(item).find('.propVal').val();
                            $(selectStamp + (!!_name?' .'+_name:'') ).attr(key,val);
                        }else{
                            timers(function(){
                                layer.msg('key请按照属性规则，以字母开头的英文内容，可出现下划线及减号');
                            });
                        }
                    }
                });
            });
        });


    };

    propsHandle.prototype.initTem = function(defProps){
        // 数据词典 特殊处理

            $(document).on("click",".temCont .lexiTree .layui-select-title",function(e) {
                $(".temCont .lexiTree .layui-form-select").not($(this).parents(".layui-form-select")).removeClass("layui-form-selected");
                $(this).parents(".dataLexiPanel").toggleClass("layui-form-selected");
                layui.stope(e);
            }).on("click","dl i",function(e) {
                layui.stope(e);
            });
            $(document).on("click",function(e) {
                $(".temCont .lexiTree .layui-form-select").removeClass(".temCont layui-form-selected");
            });

            // 上传
            $(document).on('click','.deleteFile',function(){
                $(this).parent().remove();
            });



        // 选择器 交互逻辑处理

            // 选择器部分公共全局声明
            var selectorIds = [];
            var selectorNames = [];
            var currentData = [];
            var treeId = '';
            var objSelector = {};

        // 选择器公共方法

            // 初始化列表
            function selectorTableInit(){
                var sele = $("[lay-id='selectorListTab']").find(".filter-value");
                var whereNew = {};
                whereNew[objSelector.where.id] = treeId;
                whereNew[objSelector.where.name] = sele.val();
                
                
                table.render({
                    elem: '#selectorListTab',
                    method: 'get',
                    url: serverPath.formPath + setter.sysLinkPath + objSelector.server,
                    page: true,
                    // height: 'full-510',
                    where: whereNew,
                    toolbar:'#headerManagement',
                    cols: [objSelector.cols],
                    parseData: function (res) {
                        currentData = res.data;
                        if( selectorIds.length > 0 ){
                            for(var i = 0; i < currentData.length; i++){
                            for(var j = 0; j < selectorIds.length; j++){
                                if(currentData[i][objSelector.id] === selectorIds[j]){
                                    currentData[i].LAY_CHECKED = true;
                                }
                            }
                            }
                        }
                    }
                });
                form.val('selectorQueryForm',{
                    'selectorSearch':sele.val()
                });
            }
            // 初始化选中列表部分
            function selectorListInit(){
                $('.selectorTake').html('');
                for(var i = 0; i < selectorIds.length;i++){
                    $('.selectorTake').append('<li><p>'+selectorNames[i]+'</p><i trId='+selectorIds[i]+' class="layui-icon layui-icon-delete selectorTakeDel"></i></li>');
                }
            }

            // 初始化机构树
            function selectorTabQuery(){
                $.ajax({
                    url: serverPath.formPath + setter.sysLinkPath + 'sysOrg/list',
                    type: "GET",
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function(result) {
                        var zNodes = result.data;
                        if(zNodes.length>0){
                            treeId = zNodes[0].orgId;
                            var setting = {
                                view: {
                                    showLine: false
                                },
                                callback: {
                                    onClick: function(event, treeName, treeNode, clickFlag){
                                        treeId = treeNode.orgId;
                                        selectorTableInit();
                                            
                                    }
                                }
                            },
                            treeObj = $.fn.zTree.init($('#orgTree'), setting, zNodes),
                            node = treeObj.getNodeByParam("orgId", treeId);
                            treeObj.selectNode(node);
                    
                            selectorTableInit();
                            selectorListInit();

                            totalFilter.init('selectorListTab');

                            table.on('checkbox(selectorListTab)', function (obj) {
                                if(obj.type === 'one'){
                                    if(obj.checked){
                                        selectorIds.push(obj.data[objSelector.id]);
                                        selectorNames.push(obj.data[objSelector.name]);
                                    }else{
                                        var ind = selectorIds.indexOf(obj.data[objSelector.id]);
                                        selectorIds.splice(ind,1);
                                        selectorNames.splice(ind,1);
                                    }
                                }else{
                                    for(var k = 0; k < currentData.length; k ++){
                                        var indA = selectorIds.indexOf(currentData[k][objSelector.id]);
                                        if(obj.checked){
                                            if(indA < 0){
                                                selectorIds.push(currentData[k][objSelector.id]);
                                                selectorNames.push(currentData[k][objSelector.name]);
                                            }
                                        }else{
                                            if(indA > -1){
                                                selectorIds.splice(indA,1);
                                                selectorNames.splice(indA,1);
                                            }
                                        }
                                    }
                                        
                                }

                                selectorListInit();
                            });

                            table.on('radio(selectorListTab)', function (obj) {
                                selectorIds = [obj.data[objSelector.id]];
                                selectorNames = [obj.data[objSelector.name]];
                                selectorListInit();
                            });

                            table.on('toolbar(selectorListTab)', function (obj) {
                                switch (obj.event) {
                                    case 'query':
                                    selectorTableInit();
                                    totalFilter.init('selectorListTab');
                                    break;
                                }
                            });
                                


                        }
                    }
                });
            }

            // 选择器触发事件
            $(document).on("click",defProps.selectorBtn,function(){
                var input = $(this).parent().find('input'),
                type = $(this).attr('typeid');
                selectorIds = !!input.attr('ids') ? input.attr('ids').split(',') : [];
                selectorNames= !!input.val() ? input.val().split(',') : [];
                if(type === '6' || type === '18'){
                    // 组织
                    objSelector.server = 'sysOrg/listFlatSelector';
                    objSelector.where = {
                        id:'Q_orgId_SL',
                        name:'Q_orgName_SL'
                    };
                    objSelector.id = 'orgId';
                    objSelector.name = 'name';
                    objSelector.cols = [
                        {type: type === '6' ? 'checkbox' : 'radio'},
                        {field: 'orgId', title: 'ID', sort: true, hide: true},
                        {field: 'name', title: '组织名称', width: 160,sort: false},
                        {field: 'orgPathname', width: 230, title: '所属组织',sort: false}
                    ];
                }else if(type === '8' || type === '4'){
                    // 用户
                    objSelector.server = 'sysUser/list';
                    objSelector.where = {
                        id:'orgId',
                        name:'Q_fullName_SL'
                    };
                    objSelector.id = 'userId';
                    objSelector.name = 'fullName';
                    objSelector.cols = [
                        {type: type === '8' ? 'checkbox' : 'radio'},
                        {field: 'userId', title: 'ID', sort: true, hide: true},
                        {field: 'fullName', title: '姓名', width: 160,sort: false},
                        {field: 'orgName', width: 230, title: '所属组织',sort: false}
                    ];
                } else if(type === '5' || type === '17'){
                    // 角色
                    objSelector.server = 'sysRole/list';
                    objSelector.where = {
                        id:'orgId',
                        name:'Q_roleName_SL'
                    };
                    objSelector.id = 'roleId';
                    objSelector.name = 'roleName';
                    objSelector.cols = [
                        {type: type === '5' ? 'checkbox' : 'radio'},
                        {field: 'roleId', title: 'ID', sort: true, hide: true},
                        {field: 'roleName', title: '角色', width: 160,sort: false},
                        {field: 'systemName', width: 230, title: '子系统',sort: false}
                    ];
                }
                // 选择器模板
                $.ajax({
                    url: serverPath.formPath + setter.formLinkPath + 'formDef/view/formDesign/moulds/template/selector/selectorTme',
                    type:'GET',
                    success:function(res){
                        // 选择器弹窗
                        layer.open({
                            type:'1',
                            content:res,
                            title:'选择器',
                            area:['860px','580px'],
                            btn:['保存', '撤销', '取消'],
                            btnAlign:'c',
                            skin:'form-pop-selector',
                            yes: function(index, layero){
                                // 确定
                                input.val(selectorNames);
                                input.attr('ids',selectorIds);
                                layer.close(index);
                            },
                            btn2: function(index, layero){
                                // 撤销
                                selectorIds = [];
                                selectorNames = [];
                                selectorTableInit();
                                selectorListInit();
                                return false;
                            },
                            btn3: function(index, layero){
                                // 取消
                                selectorIds = [];
                                selectorNames = [];
                            },
                            cancel:function(){
                                // 取消
                                selectorIds = [];
                                selectorNames = [];
                            }
                
                        });
                        selectorTabQuery();          
                    }
                });
                
            });
 

            // 选择器已选择删除事件
            $(document).on("click",'.selectorTakeDel',function(){
                var ind = selectorIds.indexOf($(this).attr('trId'));
                selectorIds.splice(ind,1);
                selectorNames.splice(ind,1);
                selectorListInit();
                selectorTableInit();
            });
      

    };
        
    








    exports('propsHandle', propsHandle);
});





